#include <iostream>

using namespace std;

// 检查 x 是否满足二次同余方程 Ax^2 + Bx + C ≡ 0 (mod p)
bool check(int A, int B, int C, int p, int x) {
    long long left = (1LL * A * x * x + 1LL * B * x + C) % p;
    return left == 0;
}

// 求解最小非负整数 x 满足二次同余方程
int solve(int A, int B, int C, int p) {
    for (int x = 0; x < p; ++x) {
        if ( check(A, B, C, p, x)) {
            return x;
        }
    }
    return -1;
}

int main() {
    int A, B, C, p;
    while (cin >> A >> B >> C >> p) {
        int result = solve(A, B, C, p);
        cout << result << endl;
    }
    return 0;
}
